package cn.chair.controller.admin;

import cn.chair.dao.WebBannerDao;
import cn.chair.entity.WebBanner;
import cn.chair.util.SmallUtil;
import life.innovation.builder.SqlBuilder;
import life.innovation.exception.DataWriteException;
import life.innovation.exception.ResourceNotFoundException;
import life.innovation.exception.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping(value = "banner")
@RestController
public class WebBannerController {

    @Autowired
    @Lazy
    private WebBannerDao webBannerDao;

    @PostMapping(value = "getBanner")
    public List<WebBanner> getBanners(){
        return  webBannerDao.find(SqlBuilder.init());
    }

    @GetMapping(value = "{id}")
    public WebBanner getBanner(@PathVariable int id) throws ResourceNotFoundException {

        WebBanner banner = webBannerDao.findOne(SqlBuilder.init().where("id",id));
        if(banner == null){
            throw new ResourceNotFoundException("error banner missing");
        }

        return banner;
    }

    @GetMapping(value="updateBanner/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void  updateBanner(HttpServletRequest request, @PathVariable int id, @RequestParam String url, @RequestParam String image) throws ResourceNotFoundException, DataWriteException, UnauthorizedException {
        WebBanner webBanner = webBannerDao.findOne(SqlBuilder.init().where("id",id));
        if(webBanner == null){
            throw new ResourceNotFoundException("error banner missing");
        }
        webBanner.setUrl(url);
        webBanner.setImage(image);
        webBannerDao.update(webBanner);
    }

}
